import pymysql


class DBUtil(object):
    conn = None  # 存储数据库连接

    @classmethod
    def __get_conn(cls):
        """获取数据库连接，并返回"""
        if cls.conn is None:
            cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                                       password="iHRM_student_2021", database="ihrm", charset="utf8")
        return cls.conn

    @classmethod
    def __close_conn(cls):
        if cls.conn:
            cls.conn.close()
            cls.conn = None

    @classmethod
    def select_one(cls, sql):
        cursor = None
        result = None
        try:
            # 创建数据库连接
            conn = cls.__get_conn()
            # 获取游标
            cursor = conn.cursor()
            # 执行sql
            cursor.execute(sql)
            # 保存执行结果的第一条 fetchone()
            result = cursor.fetchone()
        except Exception as e:
            print(e)
            raise e
        finally:
            # 关闭游标
            if cursor:
                cursor.close()
            # 关闭数据库连接
            cls.__close_conn()
            return result

    @classmethod
    def uid_db(cls, sql):
        cursor = None
        try:
            # 创建数据库连接
            conn = cls.__get_conn()
            # 获取游标
            cursor = conn.cursor()
            # 执行sql，提交事务
            cursor.execute(sql)
            # 提交事务
            conn.commit()
        except Exception as e:
            print(e)
            # 事务回滚
            if cls.conn:
                cls.conn.rollback()
            raise e
        finally:
            # 关闭游标
            if cursor:
                cursor.close()
            # 关闭数据库连接
            cls.__close_conn()


if __name__ == '__main__':
    data = DBUtil.select_one("select * from t_book;")
    print(data)
    # sql = "insert into t_book (id, title, pub_date) values(33, '西游记86', '1986-01-01');"
    # DBUtil.uid_db(sql)
